#EEG_preprocess.py
import numpy as np
import scipy.io
import scipy.signal as signal
from scipy.signal import butter
from scipy.io import savemat

#载入数据
data_train = scipy.io.loadmat(r'Competition_train.mat')
#data_x_test = scipy.io.loadmat(r'D:\WZR\BCI_data\3\Competition_test.mat')
#y_test = np.loadtxt(r'D:\WZR\BCI_data\3\true_labels.txt',encoding="utf-8")
x_data = data_train['X']
y_data = data_train['Y']

#预处理数据
##预处理x
###滤波
def butter_bandpass_filter(data, lowcut, highcut, fs, N=2):
    b, a = butter_bandpass(lowcut, highcut, fs, N=N)
    y = signal.filtfilt(b, a, data)
    return y

def butter_bandpass(lowcut, highcut, fs, N=2):
    Wn=[lowcut*2/fs, highcut*2/fs]
    b, a = butter(N, Wn, btype='bandpass')
    return b, a

x_data=butter_bandpass_filter(x_data,8,13,1000)

###降采样
sample=300 #采样数
x_data=signal.resample(x_data,sample,axis=-1)
###规范化
def normalize(data):
    # print("原始数据：")
    # print("var: %.4f" % np.var(x_data))
    # print("mean: %.4f" % np.mean(x_data))
    #
    # normalizer = Normalization(axis=-1)
    # normalizer.adapt(x_data)
    #
    # normalized_data = normalizer(x_data)
    # print("规范化数据：")
    # print("var: %.4f" % np.var(normalized_data))
    # print("mean: %.4f" % np.mean(normalized_data))
    data=data.astype('float32')
    print("原始数据：")
    max=data.max()
    min=data.min()
    print("最大值=",max)
    print("最小值=",min)
    if abs(max)>abs(min):
        m=abs(max)
    else:
        m=abs(min)
    data/=m
    print("处理后数据：")
    max=data.max()
    min=data.min()
    print("最大值=",max)
    print("最小值=",min)
    return data

x_data=normalize(x_data)

##预处理y
def prep_y(y):
    tmp = []
    for i in y:
        if i == 1:
            tmp.append([1, 0])
        elif i == -1:
            tmp.append([0, 1])
    y = np.array(tmp)

    return y.astype('float32')

y_data = prep_y(y_data)
data = {"X": x_data, "Y": y_data}
savemat("data_preprocessed.mat", data)
print("data has been preprocessed.mat")
